package com.tenglong.teacher.ui.register;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ClassPathResource;
import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.netease.nim.uikit.common.ToastHelper;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.WebActivity;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.common.view.XEditText;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PersonRegisterActivity extends BaseActivity implements  XEditText.DrawableRightListener {

    private EditText phone, verificationCode;
    private XEditText loginPasswork;
    private TextView getVerificationCode, dear, tvComplete, btnDear, name,companyName;
    private CountDownTimer mDownTimer;
    private String codeString="";
    private Handler handler;
    private String urlString= IpUtils.Ips[0];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_register);
        initView();
        initHandler();
        setListeners();
    }

    private void setListeners() {
        companyName.setOnClickListener(this);
        dear.setOnClickListener(this);
        btnDear.setOnClickListener(this);
        tvComplete.setOnClickListener(this);
        getVerificationCode.setOnClickListener(this);
        loginPasswork.setDrawableRightListener(this);

    }
    public void initHandler() {
        handler = new Handler() {
            public void handleMessage(Message msg) {
                dismissProgressDialog();
                if (msg.what == -10) {
                    ToastHelper.showToast(PersonRegisterActivity.this,"验证码已经发出");
                    mDownTimer.start();
                }else if(msg.what == -11){
                    ToastHelper.showToast(PersonRegisterActivity.this,"验证码短信1小时内同一手机号发送次数不能超过3次");
                }else if(msg.what == -12){
                    ToastHelper.showToast(PersonRegisterActivity.this,"验证码发送失败");
                }
            }
        };
    }
    private void initView() {
        setTitle("注册");
        companyName=findViewById(R.id.companyName);
        phone = findViewById(R.id.phone);
        verificationCode = findViewById(R.id.verificationCode);
        getVerificationCode = findViewById(R.id.getVerificationCode);
        loginPasswork = findViewById(R.id.loginPasswork);
        name = findViewById(R.id.name);
        dear = findViewById(R.id.dear);
        btnDear = findViewById(R.id.btnDear);
        tvComplete = findViewById(R.id.tvComplete);
        onClick(dear);
        mDownTimer = new CountDownTimer(60 * 1000 + 500, 1 * 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                getVerificationCode.setTextColor(Color.parseColor("#b8b8b8"));
                getVerificationCode.setText("重发发送(" + millisUntilFinished / 1000 + ")");
                getVerificationCode.setClickable(false);
                getVerificationCode.setEnabled(false);
            }

            @Override
            public void onFinish() {
                getVerificationCode.setText("获取验证码 ");
                getVerificationCode.setClickable(true);
                getVerificationCode.setEnabled(true);
                getVerificationCode.setTextColor(ContextCompat.getColor(PersonRegisterActivity.this, R.color.theme_green));
            }
        };
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.companyName:
                startActivityForResult(new Intent(this,ChoiceSchoolListActivity.class),100);
                break;
            case R.id.dear:
                boolean selecte = dear.isSelected();
                tvComplete.setClickable(!selecte);
                tvComplete.setEnabled(!selecte);
                tvComplete.setAlpha(selecte ? (float) 0.5 : 1);
                dear.setSelected(!selecte);
                break;
            case R.id.btnDear:
                Intent intent = new Intent();
                intent.setClass(this,WebActivity.class);
                intent.putExtra(WebActivity.KEY_WEB_URL,"/printed/userAgreement.html");
                startActivity(intent);
                break;
            case R.id.tvComplete:
                if (TextUtils.isEmpty(name.getText().toString().trim())) {
                    ToastUtils.showCenterToast("用户名称不能为空");
                    return;
                }
                if (!ClassPathResource.isMobileNO(phone.getText().toString().trim())) {
                    ToastUtils.showCenterToast("手机号码不正确");
                    return;
                }
                if (TextUtils.isEmpty(verificationCode.getText().toString().trim())) {
                    ToastUtils.showCenterToast("验证码不能为空");
                    return;
                }
                if (!verificationCode.getText().toString().trim().equals(codeString)) {
                    ToastHelper.showToast(this,"验证码错误");
                    return;
                }
                if (loginPasswork.getText().toString().trim().length() < 6) {
                    ToastUtils.showCenterToast("密码不能少于6位");
                    return;
                }
                request();
                break;
            case R.id.getVerificationCode:
                if (!ClassPathResource.isMobileNO(phone.getText().toString().trim())) {
                    ToastUtils.showCenterToast("手机号码不正确");
                    return;
                }
                String phoneString =phone.getText().toString();
                codeString= Utils.getCodeString();
                postDataWithParame(phoneString,codeString);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==100 && data!=null){
            if(data.hasExtra("companyInfo")){
                ClientUserInfo info = (ClientUserInfo) data.getSerializableExtra("companyInfo");
                companyName.setText(info.getCompanyName());
                companyName.setTag(info.getId());
                if(!StringUtil.isEmpty(info.getUrl())){
                    urlString=info.getUrl();
                }
            }
        }
    }

    private void request() {
        setProgressDialogMessage("账号注册中...");
        ClientUserInfo info = new ClientUserInfo();
        if(companyName.getTag()!=null){
            String school=companyName.getTag().toString();
            if(!StringUtil.isEmpty(school)){
                info.setCompanyId(school);
            }
        }
        info.setPhone(phone.getText().toString().trim());
        info.setPassword(loginPasswork.getText().toString().trim());
        info.setUserName(name.getText().toString().trim());
        CreateRequestEntity.getWebServiceUrl(urlString).personRegister(info).enqueue(new Callback<BaseResult<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    ToastUtils.showCenterToast("账号注册成功");
                    Intent intent = new Intent();
                    intent.putExtra(GlobalConstant.RESULT_CODE_REGISTER_PHONE,phone.getText().toString().trim());
                    intent.putExtra(GlobalConstant.RESULT_CODE_REGISTER_PASSWORD,loginPasswork.getText().toString().trim());
                    setResult(Activity.RESULT_OK,intent);
                    finish();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDownTimer.onFinish();
        mDownTimer.cancel();
        mDownTimer = null;
    }

    @Override
    public void onDrawableRightClick(View view) {
        EditText editText = (EditText) view;
        int length = editText.getText().toString().length();
        if (TextUtils.isEmpty(editText.getText().toString())) {
            if (!editText.isSelected()) {
                ToastUtils.showCenterToast("请先输入密码");
                return;
            }
        }
        editText.setSelected(!editText.isSelected());
        if (editText.isSelected()) {
            //如果选中，显示密码
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            //否则隐藏密码
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        editText.setSelection(length);
    }
    private void postDataWithParame(String phone,String code) {
        showProgressDialog("验证码发送中...");
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("apikey","69ad78659a9e7597a5e16b4511fa55a7");//传递键值对参数
        formBody.add("text","【吉鹿学习】您的验证码是"+code+"。如非本人操作，请忽略本短信");//传递键值对参数
        formBody.add("mobile",phone);//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url("https://sms.yunpian.com/v2/sms/single_send.json")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                handler.sendEmptyMessage(-12);
            }
            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                if(response.isSuccessful()){//回调的方法执行在子线程。
                    handler.sendEmptyMessage(-10);
                }else{
                    handler.sendEmptyMessage(-11);
                }
            }
        });
    }
}
